<?php

class Application_Model_AssocObjImgMapper{

	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_AssocObjImg');
		}
		return $this->_dbTable;
	}
	
	/**
	 * Save the id_object and the id_image in the assoc table
	 * @param Application_Model_AssocObjImg $assocobjimg
	 * @return int the row id of the insert in the data base
	 */
	public function save(Application_Model_AssocObjImg $assocobjimg)
	{
		$data = array(
				'id_object'   	=> $assocobjimg->getObjectId(),
				'id_image'	=> $assocobjimg->getImageId(),
		);
		
		if ((null === ($id1 = $assocobjimg->getObjimgId()))) {
			unset($data['id_objimg']);
			return $this->getDbTable()->insert($data);
		} 
	}
	
	/**
	 * Find the images list of the object 
	 * 
	 * @param int $id_object
	 * @return array of the Application_Model_Image
	 */
	public function findImages($id_object)
	{
		$where = array('id_object = ?' => $id_object);
		$rows = new Zend_Db_Table_Row();
		$rows = $this->getDbTable()->fetchAll($where);
		if (0 == count($rows)) {
			return;
		}
		
		$images = array();
		foreach ($rows as $row)
		{
			$imageMapper = new Application_Model_ImageMapper();
			$image = $imageMapper->find($row->id_image, new Application_Model_Image());	
			$images[] = $image;
		}
		return $images;
	}
	public function saveOfferAddresses(int $id_offer,array $addresses)
	{
		
		foreach($addresses as $address)
		{
			$data = array(
					'id_offer'   	=> $id_offer,
					'id_address'	=> $address->getAddressId(),
			);
			$this->getDbTable()->insert($data);
		}
		
	}
	
	public function delete($where){
		$result = $this->getDbTable()->fetchAll($where);
		if (0 != count($result)) {
			$this->getDbTable()->delete($where);
		}
	}
	
	
}